package com.niodata.dp.web.security;

import com.niodata.dp.core.service.SystemService;
import com.niodata.dp.core.usermgr.model.GroupInfo;
import com.niodata.dp.core.usermgr.model.UserGroup;
import com.niodata.dp.core.usermgr.model.UserInfo;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

public class DpUserDetails implements UserDetails {

  private static final long serialVersionUID = 5743928605405494290L;
  private final Set authorities;
  private final UserInfo userInfo;
  private final List<UserGroup> userGroupList;
  private final List<SystemService> serviceInfos;
  private final List<GroupInfo> groupInfoList;


  /**
   * dp user details.
   *
   * @param userInfo userInfo
   * @param userGroupList userGroupList
   * @param groupInfoList groupInfoList
   */
  public DpUserDetails(UserInfo userInfo, List<UserGroup> userGroupList,
        List<GroupInfo> groupInfoList, List<SystemService> serviceInfos) {
    this.userGroupList = userGroupList;
    this.serviceInfos = serviceInfos;
    this.groupInfoList = groupInfoList;

    authorities = new HashSet<>();
    for (UserGroup ug : userGroupList) {
      authorities.add(new SimpleGrantedAuthority(ug.getRole().toString()));
    }
    authorities.add(new SimpleGrantedAuthority(userInfo.getRole().toString()));
    this.userInfo = userInfo;
  }

  public UserInfo getUserInfo() {
    return this.userInfo;
  }

  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {
    return this.authorities;
  }

  @Override
  public String getPassword() {
    return userInfo.getPassword();
  }


  @Override
  public String getUsername() {
    return userInfo.getLoginName();
  }

  @Override
  public boolean isAccountNonExpired() {
    return true;
  }

  @Override
  public boolean isAccountNonLocked() {
    return true;
  }

  @Override
  public boolean isCredentialsNonExpired() {
    return true;
  }

  @Override
  public boolean isEnabled() {
    return true;
  }

  public List<SystemService> getServiceInfos() {
    return serviceInfos;
  }

  public List<UserGroup> getUserGroupList() {
    return userGroupList;
  }

  public List<GroupInfo> getGroupInfoList() {
    return groupInfoList;
  }

}
